<?php
namespace App\Services\Agent\Agent;

use App\Models\Agent\Agent;
use App\Models\Agent\Software;
use App\Models\Deal\Deal;
use App\Models\User\Users;
use App\Models\User\UsersInfo;
use Illuminate\Support\Facades\DB;
use Illuminate\Hashing\BcryptHasher;
use App\Http\Controllers\Admin\AliController;

class AgentLogic
{
    // 添加代理
    public function addAgent($data)
    {
        if($data['card_type']==1 && strlen($data['card'])!=18) {
            return verify_err(null, '身份证号为18位');
        }
        if(!empty($data['weixin'])) {
            $weixin = Agent::where('weixin', '=', $data['weixin'])->get()->toArray();
            if (!empty($weixin)) {
                return verify_err(null, '微信号重复');
            }
        }
        if(!empty($data['weibo'])) {
            $weibo = Agent::where('weibo', '=', $data['weibo'])->get()->toArray();
            if (!empty($weibo)) {
                return verify_err(null, '微博号重复');
            }
        }
        unset($data['token']);
        $data['create_at'] = date('Y-m-d H:i:s');
        $data['user_name'] = $data['phone'];
        $data['expired_time'] = strtotime("+".$data['fix_choose']." year", strtotime($data['fix_date']));
        $data['memory_day'] = [];
        if(!empty($data['memory_day1']))
            $data['memory_day'][] = ['day' => $data['memory_day1'], 'des' => $data['memory_des1']];

        if(!empty($data['memory_day2']))
            $data['memory_day'][] = ['day' => $data['memory_day2'], 'des' => $data['memory_des2']];

        if(!empty($data['memory_day3']))
            $data['memory_day'][] = ['day' => $data['memory_day3'], 'des' => $data['memory_des3']];

        $data['memory_day'] = serialize($data['memory_day']);
        unset($data['memory_day1'], $data['memory_des1'], $data['memory_day2'], $data['memory_des2'], $data['memory_day3'], $data['memory_des3']);
        $data['password'] = md5($data['phone']);
        $software = Software::select()->where('agent_id','=',0)->orderBy('id')->first()->toArray();
        $data['software_id'] = $software['software_id'];
        $res = Agent::insertGetId($data);
        $s = Software::where('id','=',$software['id'])->update(['agent_id'=>$res]);
        $ali = AliController::aliSmsAccount($data['phone']);
        $aliRes = json_decode($ali);
        if($aliRes->Code!="OK"){
            Log::info($data['phone'].'发送失败');
            return auto_failure($data['phone'],'发送短信失败');
        }
        if ($res && $s) {
            return auto_return(['id' => $data],'添加成功！');
        } else {
            return auto_failure('添加失败','',0);
        }
    }

    //代理列表
    public function agentList($data){
//        DB::listen(function ($sql) {
//            var_dump($sql->sql, $sql->bindings);
//        });
//        dd($data);
        $now = time();
        $nextmonth = strtotime("+1 months", time());
        $sort = 'asc';
        !empty($data['count']) && $sort = $data['count'];
        $query = Agent::withCount('users_info')->orderBy('id',$sort);
        isset($data['status']) && $query->where('status', '=', $data['status']);
        !empty($data['simple_name']) && $query->where('simple_name','like','%'.$data['simple_name'].'%');
        !empty($data['phone_name']) && $query->where('phone_name','like','%'.$data['phone_name'].'%');
        !empty($data['fix_date']) && $query->where('fix_date','=',$data['fix_date']);
        !empty($data['agent_type']) && $query->where('agent_type','=',$data['agent_type']);
        !empty($data['main']) && $query->where('main','=',$data['main']);
        if(!empty($data['expired']) && $data['expired']==1){$query->where('expired_time','<',$now);}
        if(!empty($data['expired']) && $data['expired']==2){$query->where('expired_time','<',$nextmonth)->where('expired_time', '>', $now);}
        $res=$query->paginate(10);
        return auto_return($res,'返回数据成功！');
    }

    //获取代理列表（不分页）
    public function agentListNoPage ($data)
    {
        $now = strtotime("now");
        $nextmonth = strtotime("+3 months", strtotime("now"));
        $premonth = strtotime("-3 months", strtotime("now"));
        $query = Agent::withCount('users_info')->orderBy('id','desc');
        !empty($data['simple_name']) && $query->where('simple_name','=',$data['simple_name']);
        !empty($data['phone_name']) && $query->where('phone_name','=',$data['phone_name']);
        !empty($data['fix_data']) && $query->where('fix_data','=',$data['fix_data']);
        !empty($data['agent_type']) && $query->where('agent_type','=',$data['agent_type']);
        !empty($data['main']) && $query->where('main','=',$data['main']);
        !empty($data['status']) && $query->where('status','=',$data['status']);
        if(!empty($data['expired']) && $data['expired']==2){$query->where('expired_time','<',$now);}
        if(!empty($data['expired']) && $data['expired']==2){$query->where('expired_time','<',$nextmonth)->where('expired_time','>',$premonth);}
        $res=$query->get()->toArray();
        return auto_return($res,'返回数据成功！');
    }

    //代理详情
    public function agentDetail($data){
        $res = Agent::withCount('users_info')->with(['deal'=>function($query){
            $query->where('type', '=', '代理');
        }])->where('id','=',$data['id'])->get()->toArray();
        $res[0]['memory_day'] = unserialize($res[0]['memory_day']);
        return auto_return($res,'返回数据成功！');
    }

    //修改代理
    public function updateAgent($data){
        $data['memory_day'] = [];
        if(!empty($data['memory_day1']))
            $data['memory_day'][] = ['day' => $data['memory_day1'], 'des' => $data['memory_des1']];

        if(!empty($data['memory_day2']))
            $data['memory_day'][] = ['day' => $data['memory_day2'], 'des' => $data['memory_des2']];

        if(!empty($data['memory_day3']))
            $data['memory_day'][] = ['day' => $data['memory_day3'], 'des' => $data['memory_des3']];

        $data['memory_day'] = serialize($data['memory_day']);
        unset($data['memory_day1']);
        unset($data['memory_des1']);
        unset($data['memory_day2']);
        unset($data['memory_des2']);
        unset($data['memory_day3']);
        unset($data['memory_des3']);
        unset($data['token']);
        $res = Agent::where('id','=',$data['id'])->update($data);
        return auto_return(['id'=>$res],'返回数据成功！');
    }

    //根据agent_id查看用户信息
    public function userByAgentId($data){
        $res = UsersInfo::where('software_id','=',$data['software_id'])->get()->toArray();
        return auto_return($res,'返回数据成功！');
    }

    //处理违约
    public function deal($data){
        unset($data['token']);
        if($data['deal_type']==100){
            $dead_time = strtotime("+".$data['deal_type']." year", strtotime('now'));
        }else{
            $dead_time = strtotime("+".$data['deal_type']." days", strtotime('now'));
        }
        if($data['type'] == '代理'){
            $agent = Agent::where('id','=',$data['user_id'])->update(['status'=>3,'dead_time'=>$dead_time]);
            $deal = Deal::insert($data);
        }else{
            $agent = UsersInfo::where('id','=',$data['user_id'])->update(['status'=>3,'dead_time'=>$dead_time]);
            $deal = Deal::insert($data);
        }
        $res[] = $agent;$res[] = $deal;
        return auto_return($res,'操作成功！');
    }

    //注销处理
    public function cancle($data){
        if($data['type'] == '代理'){
            $agent = Agent::where('id','=',$data['id'])->update(['status'=>1]);
        }else{
            $agent = UsersInfo::where('id','=',$data['id'])->update(['status'=>2]);
        }
        $res[] = $agent;
        return auto_return($res,'操作成功！');
    }

    //更新协议
    public function updateProtocol($data){
        unset($data['token']);
        if($data['type'] == '代理'){
            unset($data['type']);
            $agent = Agent::where('id','=',$data['id'])->update($data);
        }else{
            unset($data['type']);
            $agent = UsersInfo::where('id','=',$data['id'])->update($data);
        }
        $res[] = $agent;
        return auto_return($res,'操作成功！');
    }
   
}